package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.common.util.IdWorker;
import com.changgou.goods.dao.BrandMapper;
import com.changgou.goods.dao.CategoryMapper;
import com.changgou.goods.dao.SkuMapper;
import com.changgou.goods.dao.SpuMapper;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.BrandService;
import com.changgou.goods.service.SpuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.plugin.javascript.navig.Array;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/****
 * @Author:www.itheima.com
 * @Description:Spu业务层接口实现类
 * @Date 黑马畅购商城
 *****/
@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * Spu条件+分页查询
     * @param spu 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<Spu> findPage(Spu spu, int page, int size){
        //分页
        PageHelper.startPage(page,size);
        //搜索条件构建
        Example example = createExample(spu);
        //执行搜索
        return new PageInfo<Spu>(spuMapper.selectByExample(example));
    }

    /**
     * Spu分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Spu> findPage(int page, int size){
        //静态分页
        PageHelper.startPage(page,size);
        //分页查询
        return new PageInfo<Spu>(spuMapper.selectAll());
    }

    /**
     * Spu条件查询
     * @param spu
     * @return
     */
    @Override
    public List<Spu> findList(Spu spu){
        //构建查询条件
        Example example = createExample(spu);
        //根据构建的条件查询数据
        return spuMapper.selectByExample(example);
    }


    /**
     * Spu构建查询对象
     * @param spu
     * @return
     */
    public Example createExample(Spu spu){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(spu!=null){
            // 主键
            if(!StringUtils.isEmpty(spu.getId())){
                    criteria.andEqualTo("id",spu.getId());
            }
            // 货号
            if(!StringUtils.isEmpty(spu.getSn())){
                    criteria.andEqualTo("sn",spu.getSn());
            }
            // SPU名
            if(!StringUtils.isEmpty(spu.getName())){
                    criteria.andLike("name","%"+spu.getName()+"%");
            }
            // 副标题
            if(!StringUtils.isEmpty(spu.getCaption())){
                    criteria.andEqualTo("caption",spu.getCaption());
            }
            // 品牌ID
            if(!StringUtils.isEmpty(spu.getBrandId())){
                    criteria.andEqualTo("brandId",spu.getBrandId());
            }
            // 一级分类
            if(!StringUtils.isEmpty(spu.getCategory1Id())){
                    criteria.andEqualTo("category1Id",spu.getCategory1Id());
            }
            // 二级分类
            if(!StringUtils.isEmpty(spu.getCategory2Id())){
                    criteria.andEqualTo("category2Id",spu.getCategory2Id());
            }
            // 三级分类
            if(!StringUtils.isEmpty(spu.getCategory3Id())){
                    criteria.andEqualTo("category3Id",spu.getCategory3Id());
            }
            // 模板ID
            if(!StringUtils.isEmpty(spu.getTemplateId())){
                    criteria.andEqualTo("templateId",spu.getTemplateId());
            }
            // 运费模板id
            if(!StringUtils.isEmpty(spu.getFreightId())){
                    criteria.andEqualTo("freightId",spu.getFreightId());
            }
            // 图片
            if(!StringUtils.isEmpty(spu.getImage())){
                    criteria.andEqualTo("image",spu.getImage());
            }
            // 图片列表
            if(!StringUtils.isEmpty(spu.getImages())){
                    criteria.andEqualTo("images",spu.getImages());
            }
            // 售后服务
            if(!StringUtils.isEmpty(spu.getSaleService())){
                    criteria.andEqualTo("saleService",spu.getSaleService());
            }
            // 介绍
            if(!StringUtils.isEmpty(spu.getIntroduction())){
                    criteria.andEqualTo("introduction",spu.getIntroduction());
            }
            // 规格列表
            if(!StringUtils.isEmpty(spu.getSpecItems())){
                    criteria.andEqualTo("specItems",spu.getSpecItems());
            }
            // 参数列表
            if(!StringUtils.isEmpty(spu.getParaItems())){
                    criteria.andEqualTo("paraItems",spu.getParaItems());
            }
            // 销量
            if(!StringUtils.isEmpty(spu.getSaleNum())){
                    criteria.andEqualTo("saleNum",spu.getSaleNum());
            }
            // 评论数
            if(!StringUtils.isEmpty(spu.getCommentNum())){
                    criteria.andEqualTo("commentNum",spu.getCommentNum());
            }
            // 是否上架
            if(!StringUtils.isEmpty(spu.getIsMarketable())){
                    criteria.andEqualTo("isMarketable",spu.getIsMarketable());
            }
            // 是否启用规格
            if(!StringUtils.isEmpty(spu.getIsEnableSpec())){
                    criteria.andEqualTo("isEnableSpec",spu.getIsEnableSpec());
            }
            // 是否删除
            if(!StringUtils.isEmpty(spu.getIsDelete())){
                    criteria.andEqualTo("isDelete",spu.getIsDelete());
            }
            // 审核状态
            if(!StringUtils.isEmpty(spu.getStatus())){
                    criteria.andEqualTo("status",spu.getStatus());
            }
        }
        return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public Integer delete(Long id){
        Spu spu = findById(id);
        if ("0".equals(spu.getIsDelete())) {
            //先逻辑删除之后，才能物理删除
            throw new RuntimeException("此商品不能删除");
        }
        Sku sku=new Sku();
        sku.setId(spu.getId());
        skuMapper.delete(sku);
        return spuMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改Spu
     * @param spu
     */
    @Override
    public Integer update(Spu spu){
        return spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 增加Spu
     * @param spu
     */
    @Override
    public Integer add(Spu spu){
        return spuMapper.insert(spu);
    }

    /**
     * 根据ID查询Spu
     * @param id
     * @return
     */
    @Override
    public Spu findById(Long id){
        return  spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询Spu全部数据
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 保存商品spu和sku列表
     * @param goods
     * @return
     */
    @Override
    public void saveGoods(Goods goods) {
        //保存spu
        Spu spu=goods.getSpu();
        //未审核
        spu.setStatus("0");
        if (spu.getId()==null) {
            spu.setId(idWorker.nextId());
            spuMapper.insertSelective(spu);
        }else {
            spuMapper.updateByPrimaryKeySelective(spu);
            Sku sku=new Sku();
            sku.setSpuId(spu.getId());
            skuMapper.delete(sku);
        }

        //保存sku列表
        if (goods.getSkuList()!=null&&goods.getSkuList().size()>0){
            Date date=new Date();
            for (Sku sku : goods.getSkuList()) {
                sku.setId(idWorker.nextId());
                sku.setSpuId(spu.getId());
                //名称 = spu名称 + 所有规格选项的值
                String name=spu.getName();
                if (StringUtils.isEmpty(sku.getSpec())){
                    Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                    for (Map.Entry<String, String> entry : specMap.entrySet()) {
                        name+=""+entry.getValue();
                    }
                }else {
                    //设置空规格对象
                    sku.setName("{}");
                }
                //处理品牌
                sku.setName(name);
                Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
                sku.setBrandName(brand.getName());
                //处理分类
                Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
                sku.setCategoryId(category.getId());
                sku.setCategoryName(category.getName());
                sku.setCreateTime(date);
                sku.setUpdateTime(date);
                skuMapper.insertSelective(sku);
            }
        }

    }

    /**
     * 根据商品spu id 查询商品（spu+sku列表）
     * @param spuId
     * @return
     */
    @Override
    public Goods findGoodsBySpuId(Long spuId) {
        Goods goods = new Goods();
        goods.setSpu(findById(spuId));
        Sku sku=new Sku();
        sku.setSpuId(spuId);
        List<Sku> skuList = skuMapper.select(sku);
        goods.setSkuList(skuList);
        return goods;
    }

    @Override
    public void audit(Long id) {
        Spu spu=findById(id);
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已经被删除");
        }
        //已审核
        spu.setStatus("1");
        //上架:审核成功后自动上架
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 上架商品
     * @param id
     * @return
     */
    @Override
    public void put(Long id) {
        Spu spu = findById(id);
        if ("1".equals(spu.getIsDelete())){
            throw new RuntimeException("商品已经被删除！");
        }
        if ("0".equals(spu.getStatus())){
            throw new RuntimeException("审核通过之后才能上架！");
        }
        //上架
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
         * 批量上架商品
         * @param ids 商品spu id数组；在postman中请求体类似设置为：[1,2,3]
         * @return 操作结果
         */
    @Override
    public Integer putMany(Long... ids) {
            //未删除、已审核通过的才能上架
            Example example=new Example(Spu.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("isDelete","0");
            criteria.andEqualTo("status","1");
            //在选定的id范围内
            criteria.andIn("id", Arrays.asList(ids));

            //要更新的内容
            Spu spu =new Spu();
            //上架
            spu.setIsMarketable("1");
            return spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
         * 下架商品
         * @param id 商品spu id
         * @return 操作结果
         */
    @Override
    public void pull(Long id) {
        Spu spu = findById(id);
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已经被删除");
        }
        //未审核
        spu.setStatus("0");
        //下架
        spu.setIsMarketable("0");
         spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
         * 逻辑删除商品
         * @param id 商品spu id
         * @return 操作结果
         */
    @Override
    public Integer logicDelete(Long id) {
        Spu spu = findById(id);
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品已经被删除");
        }
        if ("1".equals(spu.getIsMarketable())) {
            throw new RuntimeException("商品要先下架才能删除");
        }
        //逻辑删除
        spu.setIsDelete("1");
        //设置未审核
        spu.setStatus("0");
        return spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
         * 还原被删除商品
         * @param id 商品spu id
         * @return 操作结果
         */
    @Override
    public Integer restore(Long id) {
        Spu spu = findById(id);
        if ("0".equals(spu.getIsDelete())) {
            throw new RuntimeException("商品未被删除，不需要还原");
        }

        spu.setIsDelete("0");
        //设置未上架
        spu.setStatus("0");
        return spuMapper.updateByPrimaryKeySelective(spu);
    }
}
